package com.example.BlockChain.controller;

import com.example.BlockChain.entity.EthWallet;
import com.example.BlockChain.entity.JSONObject;
import com.example.BlockChain.entity.TUser;
import com.example.BlockChain.service.UserService;
import com.example.BlockChain.utils.DateUtils;
import com.example.BlockChain.utils.EthUtils;
import com.example.BlockChain.utils.MD5Utils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;


import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.List;

import javax.annotation.Resource;

import static com.example.BlockChain.utils.EthUtils.publicKeyToAddress;

@RestController
public class UserController {

    @Resource
    private UserService userService;


    /**
     * 注册
     * @param user
     * @return
     */
    @RequestMapping(value = "/add")
    public ResponseEntity<JSONObject> add(@RequestBody TUser user) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
        JSONObject jo = new JSONObject();

        if (user.getUsername() == null || "".equals(user.getUsername())){
            jo.setCode("-1");
            jo.setMsg("用户名不能为空");
            return new ResponseEntity<JSONObject>(jo, HttpStatus.OK);
        }

        if (user.getPassword() == null || "".equals(user.getPassword())){
            jo.setCode("-1");
            jo.setMsg("密码不能为空");
            jo.setO(user);
            return new ResponseEntity<JSONObject>(jo, HttpStatus.OK);
        }

        if (user.getRole() == null || "".equals(user.getRole())){
            jo.setCode("-1");
            jo.setMsg("用户类型不能为空");
            jo.setO(user);
            return new ResponseEntity<JSONObject>(jo, HttpStatus.OK);
        }

        //数据库检查是否存在该用户
        TUser exist = userService.queryUserByUsername(user.getUsername());
        if (exist != null){
            jo.setCode("-1");
            jo.setMsg("该用户名已存在");
            return new ResponseEntity<JSONObject>(jo, HttpStatus.OK);
        }
        //jo.setO(exist);

        ECKeyPair keyPair = Keys.createEcKeyPair();
        BigInteger privateKey = keyPair.getPrivateKey();
        BigInteger publicKey = keyPair.getPublicKey();
        String address = publicKeyToAddress(publicKey);
        user.setPrivateKey(privateKey.toString(16));
        user.setPublicKey(publicKey.toString(16));
        user.setAddress(address);
        jo.setO(user);
        userService.add(user);

        jo.setCode("200");
        jo.setMsg("用户添加成功！");
        return new ResponseEntity<JSONObject>(jo, HttpStatus.OK);
    }

    /**
     * 登录
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> login(@RequestBody TUser user) {
        JSONObject jo = new JSONObject();

        // 参数校验
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            jo.setCode("-1");
            jo.setMsg("用户名不能为空");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            jo.setCode("-1");
            jo.setMsg("密码不能为空");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }
        if (user.getRole() == null || user.getRole().isEmpty()) {
            jo.setCode("-1");
            jo.setMsg("角色不能为空");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }

        jo.setO(user);

        TUser exist = userService.queryUser(user);
        if (exist == null) {
            jo.setCode("-1");
            jo.setMsg("用户不存在，请先注册");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }

        // 检查密码
        if (!user.getPassword().equals(exist.getPassword())) {
            jo.setCode("-1");
            jo.setMsg("密码错误，请重试");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }

        // 登录成功
        jo.setCode("200");
        jo.setMsg("登录成功");
        jo.setO(exist.getUserid());
        return new ResponseEntity<>(jo, HttpStatus.OK);

    }

    /*
    获取店铺列表
    * */
    @GetMapping(value = "/getStores")
    public ResponseEntity<JSONObject> getStores() {
        // 创建返回的JSON对象
        JSONObject response = new JSONObject();
        try {
            // 调用服务层方法获取店铺列
            List<TUser> stores = userService.getAllStores("商家");
            if (stores.isEmpty()) {
                // 如果店铺列表为空，返回提示信息
                response.setCode("404");
                response.setMsg("暂无店铺信息");
                return new ResponseEntity<>(response, HttpStatus.OK);
            }
            // 将店铺列表放入JSON对象
            response.setCode("200");
            response.setMsg("店铺列表获取成功");
            response.setO(stores);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            // 处理异常情况并返回错误信息
            response.setCode("500");
            response.setMsg("服务器内部错误: " + e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }



}
